/*
 * Copyright (c) 2016, Seer Tech co. tld. All rights reserved.
 * SEER TECH PROJECT: huijujz. Use is subject to license terms.
 *
 *
 *
 *
 *
 */
package com.mass.core.framework.web.filter;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JsCrossDomainFilter implements Filter {

    private String[] originAllowedList;

    public JsCrossDomainFilter(String originAllowed) {
        if (StringUtils.trimToNull(originAllowed) != null) {
            originAllowedList = originAllowed.split(",");
        } else {
            originAllowedList = new String[0];
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String origin = request.getHeader("Origin");
        if (StringUtils.trimToNull(origin) != null) {
            if (originAllowedList.length > 0) {
                if (ArrayUtils.contains(originAllowedList, origin)) {
                    response.setHeader("Access-Control-Allow-Origin", origin);
                }
            }
        }
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X_Requested_With, Content-Type, Accept, If-Modified-Since");
        filterChain.doFilter(request, response);
    }

    
    public void destroy() {

    }
}
